<script setup lang="ts" name="GoodsSku">
import { GoodsInfo, SpecValue, Spec, PathMap, Skus } from '@/types/data'
import bwPowerSet from '@/utils/power-set'
import { delay } from '@/utils/delay'
import { computed, reactive, ref, watch, watchEffect } from 'vue'

const props = defineProps<{
  goods: GoodsInfo
  skuId?: String
}>()
// const emit = defineEmits(['checkGoods'])
const emit = defineEmits<{
  (e: 'checkGoods', value: string): void
}>()
const SPLIT_STR = '★'
// soec每一项    sub 每一项中的选择项 []
const changeSelected = (spec: Spec, sub: SpecValue) => {
  // 禁用的时候不允许选中
  if (sub.disabled) return
  if (sub.selected) {
    // 如果已经是选中了，取消选中   不需要 取消
    sub.selected = false
  } else {
    // 把同级所有(包括sub)的全部取消选中   排他思想
    spec.values.forEach(v => (v.selected = false))
    // 让sub选中
    sub.selected = true
  }
  // if (sub.selected) return
  // // 禁用的时候不允许选中
  // if (sub.disabled) return
  // // 如果没选中 则选中    并且把同级所有(包括sub)的全部取消选中   排他思想
  // spec.values.forEach(item => (item.selected = false))
  // sub.selected = true
  // 在点击规格的时候，需要更新禁用状态

  // 更新禁用状态
  updateDisabledStatus(props.goods.specs, pathMap.value)
  // 更新选择状态
  // getSelectedSpec()

  if (checkedSpec.value.every(item => item)) {
    // 如果选了每个规格,更新价格 ,
    const str = checkedSpec.value.join(SPLIT_STR)
    const skuId = pathMap.value[str][0]
    // console.log(skuId)
    const sku: Skus | undefined = props.goods.skus.find(item => item.id === skuId)
    console.log(sku)
    props.goods.oldPrice = sku!.oldPrice
    props.goods.price = sku!.price
    emit('checkGoods', sku!.id)
  } else {
    emit('checkGoods', '')
  }
}

// 获取路径字典
const getPathMap = () => {
  const pathMap: PathMap = {}
  // Object.keys(props.goods).length || (await delay(2000), console.log('第一次'))
  // await delay(2000)
  console.log('wancjiazai')
  // 1. 过滤掉库存为0的sku
  // console.log(props.goods.skus)
  const skus = props.goods.skus.filter(item => item.inventory > 0)
  // console.log(skus)
  // 2. 遍历有效的sku,获取sku的幂集
  // console.log(skus)
  skus.forEach(item => {
    const arr = item.specs.map(sub => sub.valueName)
    // const key = arr.join('')
    // console.log(arr, key)
    // console.log(arr)

    // 3. 调用powerSet获取幂集
    const powerSet = bwPowerSet(arr)
    // console.log(powerSet)
    // 4. 把这些powerSet合并到一个路径字典中
    powerSet.forEach(sub => {
      const key = sub.join(SPLIT_STR)
      // console.log(key)
      // console.log(item)
      // console.log(key, pathMap)
      // 5. 判断pathMap中有没有key
      if (key in pathMap) {
        // 6. 存在
        pathMap[key].push(item.id)
      } else {
        // 7. 不存在
        pathMap[key] = [item.id]
      }
    })
  })
  console.log(pathMap)
  // 设置默认选中  需要放在 禁用的上方
  initSelectedSpec()
  updateDisabledStatus(props.goods.specs, pathMap)
  return pathMap
}
const pathMap = ref<PathMap>({})
// getPathMap().then(res => {
//   pathMap.value = getPathMap()
// })
watch(
  () => props.goods.id,
  () => {
    console.log('jiazai')
    pathMap.value = getPathMap()
  }
)
// 更新按钮的禁用状态
const updateDisabledStatus = async (specs: Spec[], pathMap: PathMap) => {
  // console.log(Object.keys(pathMap.value).length)
  // Object.keys(pathMap.value).length || (await delay(2500), console.log('第一次'))
  const selectArr = getSelectedSpec() // 选中的集合  ['', '日本', '']

  // 根据路径字典 => 更新所有的按钮specValue的状态

  specs.forEach((spec, index) => {
    spec.values.forEach(specValue => {
      // 让当前这个按钮, specValue.name(黑色) 和 selectArr 进行组合
      // 注意：这边尝试组合, 判断是否禁用时, 需要拷贝一份原数组
      const tempArr = [...selectArr]

      // console.log(tempArr)
      tempArr[index] = specValue.name // ['黑色', '日本', '']
      // console.log(tempArr)

      // 排除掉空为空的 =>  得到组合后转成字符串的key  '黑色+日本'
      const key = tempArr.filter(item => item).join(SPLIT_STR)
      console.log(key, pathMap)
      if (key in pathMap) {
        // 存在, 说明有库存, 不禁用
        specValue.disabled = false
      } else {
        // 不存在, 说明没有库存, 禁用
        specValue.disabled = true
      }
    })
  })
}
const getPrice = (arr: string[]) => {}
// 获取选中的规格
const checkedSpec = ref([] as string[])

const getSelectedSpec = () => {
  const arr: string[] = []
  // props.goods || (await delay(2000), console.log('第一次'))
  props.goods.specs.forEach(item => {
    const temp = item.values.find(sub => sub.selected)
    arr.push(temp ? temp.name : '')
  })
  // console.log(arr)
  checkedSpec.value = arr

  // console.log(arr.every(item => item)) // 每一项都选中才修改价格
  // const falg = arr.every(item => item)
  // if (falg) {
  //   const str = arr.join(SPLIT_STR)
  //   console.log(str)
  //   const skuId = pathMap.value[str]
  //   console.log(skuId)
  // }

  return arr
}

// 初始化时，设置默认选中效果
const initSelectedSpec = () => {
  const sku = props.goods.skus.find(item => item.id === props.skuId)
  // console.log(sku)
  if (!sku) return
  // 如果根据父组件传递的skuId找到了对应的sku,设置默认选中
  props.goods.specs.forEach((item, index) => {
    // 获取到sku中选中的规格
    const value = sku.specs[index].valueName //每一种被选中的规格
    // console.log(value)
    // 找出被选中规格的那一项
    const spec = item.values.find(item => item.name === value)
    // 让其选中
    spec!.selected = true
  })
}
</script>

<template>
  <div class="goods-sku">
    <dl v-for="item in goods.specs" :key="item.name">
      <dt>{{ item.name }}</dt>
      <dd>
        <template v-for="sub in item.values" :key="sub.name">
          <img v-if="sub.picture" :src="sub.picture" alt="" :title="sub.name" :class="{ selected: sub.selected, disabled: sub.disabled }" @click="changeSelected(item, sub)" />
          <span :class="{ selected: sub.selected, disabled: sub.disabled }" @click="changeSelected(item, sub)" v-else>{{ sub.name }}</span>
        </template>
      </dd>
    </dl>
  </div>
</template>
<!-- <template>
  <div class="goods-sku">
    <dl>
      <dt>颜色</dt>
      <dd>
        <img class="selected" src="https://yanxuan-item.nosdn.127.net/d77c1f9347d06565a05e606bd4f949e0.png" alt="" />
        <img class="disabled" src="https://yanxuan-item.nosdn.127.net/d77c1f9347d06565a05e606bd4f949e0.png" alt="" />
      </dd>
    </dl>
    <dl>
      <dt>尺寸</dt>
      <dd>
        <span class="disabled">10英寸</span>
        <span class="selected">20英寸</span>
        <span>30英寸</span>
      </dd>
    </dl>
    <dl>
      <dt>版本</dt>
      <dd>
        <span>美版</span>
        <span>港版</span>
      </dd>
    </dl>
  </div>
</template> -->
<style scoped lang="less">
.sku-state-mixin () {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;
  &.selected {
    border-color: @xtxColor;
  }
  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}
.goods-sku {
  padding-left: 10px;
  padding-top: 20px;
  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;
    dt {
      width: 50px;
      color: #999;
    }
    dd {
      flex: 1;
      color: #666;
      > img {
        width: 50px;
        height: 50px;
        margin-top: 5px;
        .sku-state-mixin ();
      }
      > span {
        display: inline-block;
        height: 30px;
        line-height: 30px;
        padding: 0 20px;
        margin-top: 5px;
        .sku-state-mixin ();
      }
    }
  }
}
</style>
